package com.invengo.module_check.ui.fragment.rfidsetting;

import android.app.Application;

import com.invengo.device.DeviceHelper;
import com.invengo.library_rfid.analyze.EPCAnalyzeFactory;
import com.invengo.library_rfid.analyze.EPCStrategy;
import com.invengo.library_rfid.analyze._EpcRuleTag;
import com.invengo.library_rfid.classify.BlueBean;
import com.invengo.library_rfid.classify.RfidModelImpl;
import com.invengo.library_rfid.device.ConnectState;
import com.invengo.library_rfid.entity.TagInfo;
import com.invengo.module_check.data.repsitory.common.CommonRepsitory;

import java.util.List;

import androidx.annotation.NonNull;
import androidx.databinding.ObservableField;

import java8.util.J8Arrays;
import java8.util.Optional;
import java8.util.stream.Collectors;
import me.goldze.mvvmhabit.BuildConfig;
import me.goldze.mvvmhabit.base.BaseViewModel;
import me.goldze.mvvmhabit.binding.command.BindingCommand;
import me.goldze.mvvmhabit.bus.RxBus;
import me.goldze.mvvmhabit.bus.event.SingleLiveEvent;
import me.goldze.mvvmhabit.utils.KLog;
import me.goldze.mvvmhabit.utils.ToastUtils;
import me.goldze.mvvmhabit.utils.cache.ACache;
import me.goldze.mvvmhabit.utils.cache.AKey;
import me.goldze.mvvmhabit.utils.constant.Constants;

/**
 * @author buoker
 * @version 1.0.0
 * @date 2023/10/24
 * @className java.lang.String
 */
public class RFIDSettingViewModel extends BaseViewModel<CommonRepsitory> {

    public SingleLiveEvent<String> supportType = new SingleLiveEvent<>();
    public ObservableField<String> BlueName = new ObservableField<>();
    //    public SingleLiveEvent<Antennas> antenna =new SingleLiveEvent<>();
    public ObservableField<RfidModelImpl> rfidModel = new ObservableField<>();
    public ObservableField<EPCStrategy> ruleStrategy = new ObservableField<>();
    public ObservableField<Integer> powers = new ObservableField<>();
    public ObservableField<List<Integer>> powerMeter = new ObservableField<>();
    public SingleLiveEvent<Boolean> hostControl = new SingleLiveEvent<>();

    public SingleLiveEvent<Boolean> voiceModel = new SingleLiveEvent<>();

    public SingleLiveEvent<Boolean> longPressModel = new SingleLiveEvent<>();
    public SingleLiveEvent<Boolean> autoSan = new SingleLiveEvent<>();
    public SingleLiveEvent<Boolean> autoLaunch = new SingleLiveEvent<>();
    public SingleLiveEvent<Boolean> connectState = new SingleLiveEvent<>();

    public ObservableField<Boolean> is2908GBT = new ObservableField<>(false);
    public ObservableField<Boolean> is2908G = new ObservableField<>(false);
    public ObservableField<Boolean> is2910a = new ObservableField<>(false);

    public RFIDSettingViewModel(@NonNull Application application) {
        super(application);
        initParams();
//        switch (BuildConfig.DEVICE_MODULE) {
//            case "2908GBT":
//                is2908GBT.set(true);
//                break;
//            case "2908G":
//                is2908G.set(true);
//                break;
//            case "2910a":
//                is2910a.set(true);
//                break;
//        }
    }

    public void onScanResult(TagInfo tagInfo) {

    }


    public int getPowerPosition() {
        return powers.get();
    }


    private void initParams() {
        ruleStrategy.set(EPCAnalyzeFactory.getInstance().getRuleStrategy());
        rfidModel.set(RfidModelImpl.getDefaultModel());

//        RulePosition.set(Optional.ofNullable((Integer) ACache.getInstance().getAsObject(AKey.RFIDRULE_POSITION)).orElse(0));
        //除了这里，deviceHelper那边也有配置，别忘了该这个orelse
//        ModePosition.set(Optional.ofNullable((Integer) ACache.getInstance().getAsObject(AKey.RFIDMODEL_POSITION)).orElse(1));
        int[] asObject = (int[]) ACache.getInstance().getAsObject(AKey.RFID_POWER_METER);
        boolean isSetPower = true;
        if (asObject == null) {
            isSetPower = false;
            asObject = Constants.DEFAULT_POWERMETER;
        }
        List<Integer> collect = J8Arrays.stream(asObject).boxed().collect(Collectors.toList());
        powerMeter.set(collect);
        Integer p = Optional.ofNullable((Integer) ACache.getInstance().getAsObject(AKey.RFID_POWER)).orElse(17);
        powers.set(p);
        if (!isSetPower) {
            changePower(p + "");
        }
        longPressModel.postValue(ACache.getInstance().getAsBoolean(AKey.IS_LONG_PRESS_MODEL));
        autoSan.postValue(ACache.getInstance().getAsBoolean(AKey.AUTO_SCAN_ON_FRAGMENT_OPEN));
        autoLaunch.postValue(ACache.getInstance().getAsBoolean(AKey.AUTO_SCAN_SHELF_LAUNCH));
        voiceModel.postValue(ACache.getInstance().getAsBoolean(AKey.IS_OPEN_VOICE));
        hostControl.postValue(ACache.getInstance().getAsBoolean(AKey.IS_HOST_CONTROL));
        BlueName.set(Optional.ofNullable(ACache.getInstance().getAsString(AKey.BLUETOOTH_NAME)).orElse("暂无配对蓝牙"));
        connectState.postValue(ACache.getInstance().getAsBoolean(AKey.SHOW_DEVICE_CONNECT_STATE));
    }


    public UIChangeObservable uc = new UIChangeObservable();

    public void changeRuleModel(int which) {
        EPCAnalyzeFactory.getInstance().changeRuleModel(which);
        EPCStrategy ruleStrategy = EPCAnalyzeFactory.getInstance().getRuleStrategy();
        this.ruleStrategy.set(ruleStrategy);
        RxBus.getDefault().post(ruleStrategy.getRule());

//        ACache.getInstance().put(AKey.RFIDRULE_POSITION, which);
//        RulePosition.set(which);
//        RxBus.getDefault().post(_EpcRuleTag.values()[which]);
    }

    public void changeRfidModel(int which) {
        RfidModelImpl.changeModel(which);
        RfidModelImpl model = RfidModelImpl.getDefaultModel();
        rfidModel.set(model);
        RxBus.getDefault().post(model);
    }

    public void changePower(String which) {
        ACache.getInstance().put(AKey.RFID_POWER, Integer.parseInt(which));
        powers.set(Integer.parseInt(which));
        DeviceHelper.getInstance().changePower(powers.get());
    }

    public List<String> getDeviceList() {
        return DeviceHelper.getInstance().getDeviceList();
    }

    public void changeBlueName(String text) {
        BlueName.set(text);
        ACache.getInstance().put(AKey.BLUETOOTH_NAME, text);
        BlueBean bean = new BlueBean(text);
        RxBus.getDefault().post(bean);
    }


    public class UIChangeObservable {
        public SingleLiveEvent<Boolean> powerDialogEvent = new SingleLiveEvent<>();
        public SingleLiveEvent<Void> ruleDialogEvent = new SingleLiveEvent<>();
        public SingleLiveEvent<Void> rfidModelDialogEvent = new SingleLiveEvent<>();
        public SingleLiveEvent<Integer> analyzeTestEvent = new SingleLiveEvent<>();
        public SingleLiveEvent<Integer> blueDialog = new SingleLiveEvent<>();
    }

    /**
     * 电源命令对话框
     */
    public BindingCommand powerCommandDialog = new BindingCommand(() -> {
        uc.powerDialogEvent.setValue(true);
    });


    public BindingCommand ruleModelDialog = new BindingCommand(() -> {
//        android:clickable="@{RfidModelImpl.values()[viewModel.ModePosition]!=RfidModelImpl.TID}"
        if (RfidModelImpl.getDefaultModel() == RfidModelImpl.TID) {
            ToastUtils.showShort("TID标签模式下，不需要选择解析模型");
            return;
        }
        uc.ruleDialogEvent.call();
    });

    public BindingCommand rfidModelDialog = new BindingCommand(() -> {
        uc.rfidModelDialogEvent.call();
    });
    public BindingCommand blueDialog = new BindingCommand(() -> {
        if (DeviceHelper.getInstance().getDeviceList().isEmpty()) {
            ToastUtils.showShort("暂无配对的蓝牙设备！");
            return;
        }
        uc.blueDialog.setValue(getBluePosition());
    });

    private int getBluePosition() {
        int position = getDeviceList().indexOf(BlueName.get());
        for (String s : getDeviceList()) {
            System.out.println("s = " + s + "  " + BlueName.get());
        }
        return position;
    }


    /**
     * 语音更改命令
     */
    public BindingCommand showAnalyzeDialog = new BindingCommand<>(() -> {
        uc.analyzeTestEvent.call();
    });

    public void scanType(boolean ischecked) {
        ACache.getInstance().put(AKey.IS_HOST_CONTROL, ischecked);
    }

    public void onVoiceChange(boolean ischecked) {
        DeviceHelper.getInstance().changeVoice(ischecked);
    }

    public void onKeyChange(boolean ischecked) {
        ACache.getInstance().put(AKey.IS_LONG_PRESS_MODEL, ischecked);
    }

    public void onAutoScanChange(boolean ischecked) {
        ACache.getInstance().put(AKey.AUTO_SCAN_ON_FRAGMENT_OPEN, ischecked);
    }

    public void onAutoLaunch(boolean ischecked) {
        ACache.getInstance().put(AKey.AUTO_SCAN_SHELF_LAUNCH, ischecked);
    }

    public void showConnectState(boolean ischecked) {
        ACache.getInstance().put(AKey.SHOW_DEVICE_CONNECT_STATE, ischecked);
        RxBus.getDefault().post(ischecked ? ConnectState.SHOW : ConnectState.HIDE);
    }
}
